﻿using Faser_Shop.Models.Database;
using Faser_Shop.Models.RequestModel;
using Faser_Shop.Services;
using Faser_Shop.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;

namespace Faser_Shop.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class OrderController : Controller
    {
        private readonly Faser_ShopContext _db;
        private readonly IJWTService _jwtService;

        public OrderController(Faser_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }


        /// <summary>
        /// 结算购物车中的所有商品
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public object SettlementAll()
        {
            var userId = _jwtService.GetUserId(HttpContext);
            using (var transaction = _db.Database.BeginTransaction())
            {
                // 获取当前用户的购物车商品
                var cart = _db.ShoppingCarts.Where(x => x.UserId == userId).ToList();
                // 生成订单
                var raworder = new Order
                {
                    UserId = userId,
                    OrderTotalPrice = cart.Sum(x => x.ProductQuantity * _db.Products.Find(x.ProductId).ProductPrice),
                };
                var order = _db.Orders.Add(raworder);
                _db.SaveChanges();
                // 生成订单明细
                foreach (var item in cart)
                {
                    var orderDetail = new OrderDetail
                    {
                        OrderId = raworder.OrderId,
                        ProductId = item.ProductId,
                        ProductPrice = item.Product.ProductPrice,
                        ProductQuantity = item.ProductQuantity
                    };
                    _db.OrderDetails.Add(orderDetail);
                    // 扣除商品库存
                    var product = _db.Products.Find(item.ProductId);
                    var freeStock = product.ProductStock - item.ProductQuantity;
                    if (freeStock < 0)
                    {
                        return ApiResult.PRODUCT_STOCK_NOT_ENOUGH;
                    }
                    product.ProductStock = freeStock;
                    _db.SaveChanges();
                }
                // 订单进入待发货状态
                raworder.PaymentTime = DateTime.Now;
                _db.SaveChanges();
                // 清空购物车
                _db.ShoppingCarts.RemoveRange(cart);
                _db.SaveChanges();
                transaction.Commit();
            }
            return ApiResult.SUCCESS;
        }

        /// <summary>
        /// 用户单列表
        /// </summary>
        /// <param name="status"> waitpay, shipping, completed </param>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public object UserOrderList(string status)
        {
            var userId = _jwtService.GetUserId(HttpContext);
            var orders = _db.Orders.Where(x => x.UserId == userId).ToList();
            switch (status)
            {
                case "waitpay":
                    orders = orders.Where(x => !x.PaymentTime.HasValue).ToList();
                    break;
                case "shipping":
                    orders = orders.Where(x => x.ShippingTime.HasValue).ToList();
                    break;
                case "completed ":
                    orders = orders.Where(x => x.DeliveryTime.HasValue).ToList();
                    break;
                default:
                    break;
            }
            return ApiResult.Success(orders);
        }

        /// <summary>
        /// 后台订单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize(Roles = "Admin")]
        public object AdminOrderList()
        {
            var orders = _db.Orders.ToList();
            return ApiResult.Success(orders);
        }

        /// <summary>
        /// 后台发货
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize(Roles = "Admin")]
        public object AdminDelivery([FromBody] AdminDeliveryRM model)
        {
            var logistics = _db.LogisticsWarehouses.Any(x => x.WarehouseId == model.WarehouseID);
            if (!logistics)
            {
                return ApiResult.INVALID_EXPRESS;
            }

            var order = _db.Orders.Where(x => x.OrderId == model.OrderId).FirstOrDefault();
            if (order == null)
            {
                return ApiResult.ORDER_NOT_FOUND;
            }

            using (var transaction = _db.Database.BeginTransaction())
            {

                var logisticsRecord = new LogisticsRecord
                {
                    WarehouseCode = model.WarehouseID,
                    TrackingNumber = model.TrackingNumber,
                    CreationTime = DateTime.Now
                };

                _db.LogisticsRecords.Add(logisticsRecord);
                _db.SaveChanges();

                order.TrackingId = logisticsRecord.TrackingId;
                order.ShippingTime = DateTime.Now;
                _db.SaveChanges();

                transaction.Commit();
            }

            return ApiResult.SUCCESS;
        }
    }
}
